import { Button } from '@/components/ui/button';
import { Toaster } from '@/components/ui/sonner';
import { useMessage } from './hook/useDiaoxiaomiMessage';

import { BatchCollectOperation } from '@/components/BatchCollectOperation';
import SettingsPersisted from '@/components/SettingsPersisted';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogOverlay,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import config from '@/config';
import {
  Task,
  TaskInfo,
  TaskType,
  useConcurrentRequest,
} from '@/entrypoints/hook/useConcurrentRequest';
import { importFile, saveFile } from '@/lib/filesystem';
import { name } from '@/package.json';
import { useSettingsStore } from '@/store';
import { toast } from 'sonner';
import AccountSetting from './AccountSetting';
import { usePush } from './hook/useDiaoxiaomi';
import { useProcess } from './hook/useProcess';
import { usePublic } from './hook/usePublic';
import LocalDiskInfo from './LocalDiskInfo';
import OperationMessages, { OperationMessageCategory } from './OperationMessage';
import ProcessSetting from './ProcessSetting';
import PushSetting from './PushSetting';
import { generateRandomId } from '@/lib/utils';
import PublicSeting from './PublicSeting';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';

export const restoreQueueKey = name + '-restore-process-and-push-key';
export default function App() {
  const { resetMessage, addMessage } = useMessage();
  const dispatch = useSettingsStore((state) => state.dispatch);
  const clearMessageInterval = useSettingsStore((state) => state.baseSettings.clearMessageInterval);
  const categoryOptionList = useSettingsStore((state) => state.pushSettings.categoryOptionList);
  const isResumeTask = useSettingsStore((state) => state.batchSettings.isResumeTask);

  const { enqueueTask, queue, totalTask, activeTask, completedTask, isStop, resume, clearQueue } =
    useConcurrentRequest(restoreQueueKey);
  // 提前提取出队列
  const resumeTasks = JSON.parse(localStorage.getItem(restoreQueueKey) || '[]');
  const { processProduct } = useProcess();
  const { pushProduct } = usePush();
  const {
    publicProduct,
    intervalPublicProduct,
    pause,
    isPaused,
    storageValue: publicStorageValue,
    setStorageValue: setPublicStorageValue,
    offlineProductInfos,
  } = usePublic();

  // 定时执行 accessToken 的获取
  // useGigaAccessToken();

  // async function batchReplace() {
  //   const directoryHandles = await window.showDirectoryPicker({
  //     mode: 'readwrite',
  //   });
  //   resetMessage();
  //   addMessage({
  //     category: appConfig.topMessageCategoryName,
  //     type: OperationMessageType.info,
  //     message: '成功获取提供的货号目录',
  //   });
  //   // 获取待发布的产品
  //   try {
  //     const productInfos = await getToBePublishProductInfo();
  //     console.log('待发布的产品', productInfos);
  //     addMessage({
  //       category: appConfig.topMessageCategoryName,
  //       type: OperationMessageType.info,
  //       message: '成功获取所有待发布的产品货号和 id,开始进行替换操作',
  //     });

  //     isStopRef.current = false;
  //     dispatch({
  //       type: 'update',
  //       update(draftState) {
  //         draftState.uploadStatistics = {
  //           success: 0,
  //           error: 0,
  //         };
  //       },
  //     });

  //     for await (const [name, skuIdInfoDirectoryHandle] of directoryHandles.entries()) {
  //       if (skuIdInfoDirectoryHandle.kind === 'directory') {
  //         const productInfo = productInfos.find((productInfo) => {
  //           return productInfo.skuIdInfo === name;
  //         });
  //         if (productInfo && !isStopRef.current) {
  //           // 开始进行对每一个货号的编辑替换操作
  //           try {
  //             await replaceAndSaveProductInfo(
  //               productInfo,
  //               skuIdInfoDirectoryHandle,
  //               directoryHandles,
  //             );
  //             dispatch({
  //               type: 'update',
  //               update(draftState) {
  //                 draftState.uploadStatistics.success = draftState.uploadStatistics.success + 1;
  //               },
  //             });
  //           } catch (error) {
  //             addMessage({
  //               category: productInfo.skuIdInfo!,
  //               type: OperationMessageType.error,
  //               message: `${(error as Error).message}`,
  //             });
  //             dispatch({
  //               type: 'update',
  //               update(draftState) {
  //                 draftState.uploadStatistics.error = draftState.uploadStatistics.error + 1;
  //               },
  //             });
  //           }
  //         }
  //       }
  //     }

  //     toast.success('操作完成');
  //   } catch (error) {
  //     addMessage({
  //       category: appConfig.topMessageCategoryName,
  //       type: OperationMessageType.error,
  //       message: '获取所有待发布的产品货号和 id 失败',
  //     });
  //   }
  // }

  // async function getGigaResource() {
  //   const directoryHandles = await window.showDirectoryPicker({
  //     mode: 'readwrite',
  //   });
  //   resetMessage();
  //   addMessage({
  //     category: appConfig.topMessageCategoryName,
  //     type: OperationMessageType.info,
  //     message: '成功获取提供的货号目录',
  //   });
  //   // 获取待发布的产品
  //   try {
  //     const productInfos = await getToBePublishProductInfo();
  //     console.log('待发布的产品', productInfos);
  //     addMessage({
  //       category: appConfig.topMessageCategoryName,
  //       type: OperationMessageType.info,
  //       message: '成功获取所有待发布的产品货号和 id,开始进行拉取资源的操作',
  //     });

  //     isStopRef.current = false;
  //     dispatch({
  //       type: 'update',
  //       update(draftState) {
  //         draftState.resourceStatistics = {
  //           success: 0,
  //           error: 0,
  //         };
  //       },
  //     });

  //     for await (const [name, directoryHandle] of directoryHandles.entries()) {
  //       if (directoryHandle.kind === 'directory') {
  //         const productInfo = productInfos.find((productInfo) => {
  //           return productInfo.skuIdInfo === name;
  //         });
  //         if (productInfo && !isStopRef.current) {
  //           // 开始前生成一些预置的目录,并行生成
  //           appConfig.presetDirectoryNameList.forEach((name) => {
  //             directoryHandle.getDirectoryHandle(name, {
  //               create: true,
  //             });
  //           });

  //           // 开始进行对每一个货号的资源获取操作
  //           try {
  //             await getGigaDetailResource(productInfo, directoryHandle);
  //             dispatch({
  //               type: 'update',
  //               update(draftState) {
  //                 draftState.resourceStatistics.success = draftState.resourceStatistics.success + 1;
  //               },
  //             });
  //           } catch (error) {
  //             addMessage({
  //               category: productInfo.skuIdInfo!,
  //               type: OperationMessageType.error,
  //               message: `${(error as Error).message}`,
  //             });
  //             dispatch({
  //               type: 'update',
  //               update(draftState) {
  //                 draftState.resourceStatistics.error = draftState.resourceStatistics.error + 1;
  //               },
  //             });
  //           }
  //         }
  //       }
  //     }
  //     toast.success('操作完成');
  //   } catch (error) {
  //     addMessage({
  //       category: appConfig.topMessageCategoryName,
  //       type: OperationMessageType.error,
  //       message: '获取所有待发布的产品货号和 id 失败',
  //     });
  //   }
  // }

  // function stopOperation() {
  //   isStopRef.current = true;
  //   toast.error('停止操作,不影响正在操作的产品');
  // }

  function openWebsite() {
    window.open('https://www.gigab2b.com/index.php');
    window.open(
      'http://www.postme.cn/?bd_vid=10109238579730492837#/PostMe/Article?template_id=2QSX7PrtsBGdiW7FP9UvrXgaDTg',
    );
    window.open('https://www.designkit.com/product-shoot/');
  }

  // 每隔一段时间清理一下 messages 信息
  useEffect(() => {
    const timer = setInterval(() => {
      resetMessage();
    }, clearMessageInterval * 1000);
    return () => {
      clearInterval(timer);
    };
  }, [clearMessageInterval]);

  // 批量运行任务
  const runTaskItems = useCallback(async function runTaskItem(
    collectInfoList: TaskInfo[],
    opeartion: (collectInfo: TaskInfo) => Promise<void>,
    enqueueTask: (task: Task['task']) => Promise<unknown>,
  ) {
    return await Promise.all(
      collectInfoList.map((collectInfo: TaskInfo) => {
        const taskItem = () =>
          opeartion(collectInfo).catch((error) => {
            toast.error(`${collectInfo.skuIdInfo}: ${(error as Error).message}`);
          });
        taskItem.extraData = collectInfo;
        return enqueueTask(taskItem);
      }),
    );
  }, []);

  // 恢复批量上传的任务
  const resumeTask = useCallback(
    async function resumeTask() {
      if (resumeTasks.length > 0) {
        // 清空后防止多次触发
        localStorage.setItem(restoreQueueKey, '');

        const processTasks = resumeTasks.filter((collectInfo: TaskInfo) => {
          return collectInfo.taskType === TaskType.process;
        });

        const pushTasks = resumeTasks.filter((collectInfo: TaskInfo) => {
          return collectInfo.taskType === TaskType.push;
        });
        // 并行执行所有任务
        await Promise.all([
          runTaskItems(processTasks, processProduct, enqueueTask),
          runTaskItems(pushTasks, pushProduct, enqueueTask),
        ]);
      }
    },
    [runTaskItems],
  );

  useEffect(() => {
    if (isResumeTask) {
      resumeTask();
    }
  }, [isResumeTask, resumeTask]);

  return (
    <div>
      <div>
        <AlertDialog defaultOpen={!isResumeTask && resumeTasks.length > 0}>
          <AlertDialogContent
            className="!pointer-events-auto"
            style={{
              zIndex: config.alertDialogZIndex,
            }}
          >
            <AlertDialogHeader>
              <AlertDialogTitle>任务恢复</AlertDialogTitle>
              <AlertDialogDescription>
                {`检测到上次还有 ${resumeTasks.length} 个任务未完成，是否继续任务？`}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>不继续任务</AlertDialogCancel>
              <AlertDialogAction onClick={resumeTask}>继续任务</AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
        <Dialog defaultOpen>
          <DialogTrigger asChild>
            <Button
              size="sm"
              className="px-[12px] rounded-[2px] box-content h-[32px] leading-[30px] bg-[#3ba03b]"
            >
              进入软件
            </Button>
          </DialogTrigger>
          <DialogOverlay
            className="bg-black/50"
            style={{
              zIndex: config.dialogZIndex,
            }}
          ></DialogOverlay>
          <DialogContent
            aria-describedby=""
            className="w-[90%] max-w-[1500px] h-[90vh] grid-rows-[auto_1fr]"
            style={{
              zIndex: config.dialogZIndex,
            }}
          >
            <DialogHeader>
              <DialogTitle className="text-card-foreground/80 !text-left">
                店小秘批量替换
              </DialogTitle>
            </DialogHeader>
            <div className="flex !flex-nowrap">
              <LocalDiskInfo
                enqueueTask={enqueueTask}
                totalTask={totalTask}
                completedTask={completedTask}
                runTaskItems={runTaskItems}
              ></LocalDiskInfo>
              <Tabs defaultValue="replace" className="flex flex-col grow">
                <div className="flex">
                  <TabsList className="flex-wrap justify-start">
                    <TabsTrigger value="replace">操作记录</TabsTrigger>
                    <TabsTrigger value="base-setting">基础设置</TabsTrigger>
                    <TabsTrigger value="process-setting">加工设置</TabsTrigger>
                    <TabsTrigger value="push-setting">待发布设置</TabsTrigger>
                    <TabsTrigger value="public-setting">发布设置</TabsTrigger>
                    <TabsTrigger value="account">账号设置</TabsTrigger>
                    <TabsTrigger value="batch-setting">批量设置</TabsTrigger>
                  </TabsList>
                  <SettingsPersisted className="ml-auto mr-3"></SettingsPersisted>
                  <Button
                    onClick={openWebsite}
                    size="sm"
                    className="hover:bg-[#337AB7] bg-[#428BCA]"
                  >
                    打开相关网站
                  </Button>
                </div>
                <TabsContent
                  value="replace"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader className="pb-4">
                      <CardTitle className="opacity-75 text-base">操作记录详细信息</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col pb-1">
                      <OperationMessages
                        categoryItemActionRenderer={(categoryItem) => {
                          return (
                            <OperationMessageCategory
                              categoryItem={categoryItem}
                            ></OperationMessageCategory>
                          );
                        }}
                        className="grow"
                      ></OperationMessages>
                    </CardContent>
                    <CardFooter className="block">
                      <div className="flex items-center">
                        <Button
                          size="sm"
                          onClick={intervalPublicProduct}
                          className="hover:bg-[#337AB7] bg-[#428BCA]"
                        >
                          间隔发布({isPaused === true ? '暂停' : '运行'}-
                          {publicStorageValue.publicCount}/{offlineProductInfos.current.length})
                        </Button>
                        <div className="flex px-3 gap-2 items-center py-4">
                          <Label className="whitespace-nowrap">发布数量:</Label>
                          <Input
                            value={publicStorageValue.publicMaxCount}
                            type="number"
                            onChange={(event) => {
                              setPublicStorageValue({
                                ...publicStorageValue,
                                publicMaxCount: +event.target.value,
                              });
                            }}
                            className="h-10 w-auto rounded-md border border-input px-3 py-2"
                          />
                        </div>
                        <Button
                          size="sm"
                          onClick={() => {
                            setPublicStorageValue({
                              ...publicStorageValue,
                              publicCount: 0,
                            });
                          }}
                          className="hover:bg-[#337AB7] bg-[#428BCA]"
                        >
                          重置数量
                        </Button>
                        <Button
                          size="sm"
                          variant="destructive"
                          onClick={pause}
                          className="hover:bg-destructive/90 bg-destructive ml-auto mr-3"
                        >
                          暂停发布
                        </Button>
                        <Button
                          size="sm"
                          variant="destructive"
                          onClick={resetMessage}
                          className="hover:bg-destructive/90 bg-destructive"
                        >
                          清空列表
                        </Button>
                        {/* <Button
                          size="sm"
                          variant="destructive"
                          onClick={stopOperation}
                          className="hover:bg-destructive/90 bg-destructive ml-3"
                        >
                          停止操作
                        </Button> */}
                      </div>
                      {/* <div className="flex items-center mt-3">
                        <Button
                          size="sm"
                          onClick={batchReplace}
                          className="hover:bg-[#337AB7] bg-[#428BCA]"
                        >
                          选择替换轮播图位置
                        </Button>
                        <div className="flex items-center px-3 gap-2">
                          <span>产品替换统计:</span>
                          <span className="text-[hsl(142.1_76.2%_36.3%)]">{`(${uploadStatistics.success}`}</span>
                          /<span className="text-red-500">{`${uploadStatistics.error})`}</span>
                        </div>
                      </div> */}
                      <BatchCollectOperation
                        isStop={isStop}
                        queue={queue}
                        completedTask={completedTask}
                        totalTask={totalTask}
                        activeTask={activeTask}
                        resume={resume}
                        clearQueue={clearQueue}
                      ></BatchCollectOperation>
                    </CardFooter>
                  </Card>
                </TabsContent>
                <TabsContent
                  value="base-setting"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader>
                      <CardTitle className="opacity-75 text-base">基础设置</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col">
                      <BaseSetting className="grow"></BaseSetting>
                    </CardContent>
                  </Card>
                </TabsContent>
                <TabsContent
                  value="process-setting"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader>
                      <CardTitle className="opacity-75 text-base">产品加工设置</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col">
                      <ProcessSetting className="grow"></ProcessSetting>
                    </CardContent>
                  </Card>
                </TabsContent>
                <TabsContent
                  value="push-setting"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader className="flex items-center flex-row">
                      <CardTitle className="opacity-75 text-base">店小秘待发布设置</CardTitle>
                      <Button
                        onClick={async () => {
                          const text = JSON.stringify(categoryOptionList);
                          toast.promise(saveFile(text, '预配置产品分类.json'), {
                            loading: '正在导出分类...',
                            success: '导出成功',
                            error: '导出失败',
                          });
                        }}
                        size="sm"
                        className="mr-3 ml-auto"
                      >
                        预配置产品分类导出
                      </Button>
                      <Button
                        onClick={async (params) => {
                          try {
                            const text = await importFile();
                            const categoryOptionList = JSON.parse(text!);
                            // console.log('导入的预配置产品分类', categoryOptionList);
                            dispatch({
                              type: 'update',
                              update(draftState) {
                                draftState.pushSettings.categoryOptionList.push(
                                  ...categoryOptionList.map((item: any) => {
                                    return {
                                      ...item,
                                      id: generateRandomId(), // 确保每个分类都有唯一的 ID
                                    };
                                  }),
                                );
                              },
                            });
                          } catch (error) {
                            console.error('导入预配置产品分类失败', (error as Error).message);
                          }
                        }}
                        size="sm"
                        className=""
                      >
                        预配置产品分类导入
                      </Button>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col">
                      <PushSetting className="grow"></PushSetting>
                    </CardContent>
                  </Card>
                </TabsContent>
                <TabsContent
                  value="public-setting"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader>
                      <CardTitle className="opacity-75 text-base">发布设置</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col">
                      <PublicSeting className="grow"></PublicSeting>
                    </CardContent>
                  </Card>
                </TabsContent>
                <TabsContent
                  value="account"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader>
                      <CardTitle className="opacity-75 text-base">账号设置</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col">
                      <AccountSetting className="grow"></AccountSetting>
                    </CardContent>
                  </Card>
                </TabsContent>
                <TabsContent
                  value="batch-setting"
                  className="grow flex flex-col data-[state=inactive]:hidden"
                >
                  <Card className="grow flex flex-col">
                    <CardHeader>
                      <CardTitle className="opacity-75 text-base">批量任务设置</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 grow flex flex-col">
                      <BatchSetting className="grow"></BatchSetting>
                    </CardContent>
                  </Card>
                </TabsContent>
              </Tabs>
            </div>
          </DialogContent>
        </Dialog>
      </div>
      <Toaster className="[&_li]:p-4"></Toaster>
    </div>
  );
}
